package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.NewCar1;
import com.example.demo.entity.NewCar2;
import com.example.demo.form.NewCarForm;
import com.example.demo.service.NewCar1Service;
import com.example.demo.service.NewCar2Service;

@RestController
@RequestMapping(value = "/newCar")
public class NewCarxController {
	DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	@Autowired
	private NewCar1Service newCar1DAO;
	@Autowired
	private NewCar2Service newCar2DAO;
	
	@RequestMapping(value = "/save")
	public Object save(NewCarForm Form) throws ParseException {
		Integer newCarId=Form.getId();
		Date d1 = dateFormat1.parse("1999-01-01");
		NewCar1 newCar1= new NewCar1();
		NewCar2 newCar2= new NewCar2();
		NewCar1 newcar1= new NewCar1();
		NewCar2 newcar2 = new NewCar2();
		Date d = new Date();
		if(newCarId==null) {
			newCar1.setName(Form.getName());
			newcar1 = newCar1DAO.save(newCar1);
		}else {
			newcar1=newCar1DAO.findById(newCarId);
			newcar1.setName(Form.getName());
			newCar1DAO.save(newcar1);
			List<NewCar2> list = newCar2DAO.findByNewCar(newcar1);
			for (NewCar2 newCar : list) {
				if(d1.compareTo(newCar.getXiuGaiDate())==-1) {
					d1=newCar.getXiuGaiDate();
					newcar2=newCar;
				}
			}
			newcar2.setEndDate(d);;
			newCar2DAO.save(newcar2);
		}
		BeanUtils.copyProperties(Form, newCar2, "id","name");
		newCar2.setNewCar(newcar1);
		newCar2.setXiuGaiDate(d);
		newCar2DAO.save(newCar2);
		return new AjaxResult("数据保存成功");	
	}
	
	@RequestMapping(value = "/list")
	public Object list() {
		return new AjaxResult(newCar1DAO.findAll());
	}
	
	@RequestMapping(value = "/findById")
	public Object findbyId(Integer id) throws ParseException {
	
		List<NewCar2> list = newCar2DAO.findByNewCar(newCar1DAO.findById(id));
		
		Date d = dateFormat1.parse("1999-01-01");
		NewCar2 n= new NewCar2();
		for (NewCar2 newCar2 : list) {
			if(d.compareTo(newCar2.getXiuGaiDate())==-1) {
				d=newCar2.getXiuGaiDate();
			    n=newCar2;
			}
		}
		 return new AjaxResult(n);		
	}
}
